﻿using System;
using System.Web;
using System.Configuration;
using System.IO;

namespace RN.ERP.Web.Handlers
{
    /// <summary>
    /// ExpertInfoHandler 的摘要说明
    /// </summary>
    public class ExpertInfoHandler : IHttpHandler
    {

        #region 属性和常量

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        public HttpContext Context { set; get; }
        
        /// <summary>
        /// 系统编号
        /// </summary>
        public string SysCode
        {
            get
            {
                return ConfigurationManager.AppSettings["AppId"];
            }
        }
        
        #endregion

        public void ProcessRequest(HttpContext hc)
        {
            Context = hc;
            string funcName = hc.Request["func"];
            FuncRoute(funcName);
        }

        /// <summary>
        /// 功能路由
        /// </summary>
        /// <param name="funcName">功能名称</param>
        private void FuncRoute(string funcName)
        {
            switch (funcName)
            {
                case "downloadfile": DownloadFile(); break;
                default: break;
            }
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        private void DownloadFile()
        {
            string fileName = Context.Request.QueryString["filename"];
            LoadFileFromServer("签名下载", fileName);
        }

        /// <summary>
        /// 从服务器下载文件
        /// </summary>
        /// <param name="fileName">客户端保存的文件名</param>
        /// <param name="serverFilePath">服务器端要下载的文件路径</param>
        protected void LoadFileFromServer(string fileName, string serverFilePath)
        {
            FileInfo fileInfo = new FileInfo(AppDomain.CurrentDomain.BaseDirectory + serverFilePath);
            Context.Response.Clear();
            Context.Response.ClearContent();
            Context.Response.ClearHeaders();
            Context.Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
            Context.Response.AddHeader("Content-Length", fileInfo.Length.ToString());
            Context.Response.AddHeader("Content-Transfer-Encoding", "binary");
            Context.Response.ContentType = "application/octet-stream";
            Context.Response.ContentEncoding = System.Text.Encoding.UTF8;
            Context.Response.WriteFile(fileInfo.FullName);
            Context.Response.Flush();
            Context.Response.End();
        }

        /// <summary>
        /// 输出
        /// </summary>
        private void P(string str)
        {
            Context.Response.Write(str);
            Context.Response.Flush();
            Context.Response.End();
        }
    }
}